package org.zuel.huhuForum.component;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.zuel.huhuForum.config.RabbitmqConfig;
import org.zuel.huhuForum.constant.CommunityConstant;
import org.zuel.huhuForum.model.*;
import org.zuel.huhuForum.param.Event;
import org.zuel.huhuForum.service.ICommentService;
import org.zuel.huhuForum.service.IDiscussPostService;
import org.zuel.huhuForum.service.IElasticsearchService;
import org.zuel.huhuForum.service.Impl.*;
import org.zuel.huhuForum.util.DateUtil;
import org.zuel.huhuForum.util.RedisKeyUtil;

import javax.mail.MessagingException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class Consumer implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(Consumer.class);

    @Autowired
    private MessageService messageService;

    @Autowired
    private IDiscussPostService discussPostService;

    @Autowired
    private IElasticsearchService elasticsearchService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private MainService mainService;

    @Autowired
    private SendMsg sendMsg;



    @RabbitListener(queues = RabbitmqConfig.QUEUE_MESSAGE)
    public void handleMessage(String record) {
        if (record== null) {
            logger.error("消息的内容为空");
            return ;
        }
        Event event = JSONObject.parseObject(record, Event.class);
        if (event == null) {
            logger.error("消息格式错误");
            return ;
        }

        // 发送系统通知
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(LocalDateTime.now());

        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());
        if (!event.getData().isEmpty()) { // 存储 Event 中的 Data
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }
        message.setContent(JSONObject.toJSONString(content));

        messageService.addMessage(message);
    }

    @RabbitListener(queues = RabbitmqConfig.QUEUE_DISCUSS_AD)
    public void handleDiscuss(String record){
        if (record== null ) {
            logger.error("消息的内容为空");
            return ;
        }
        Event event = JSONObject.parseObject(record, Event.class);
        if (event == null) {
            logger.error("消息格式错误");
            return ;
        }

        switch (event.getTopic()) {
            case TOPIC_PUBLISH:
                if (!event.getData().isEmpty()) {
                    if (event.getEntityId() >= 0) {
                        DiscussPost discussPost = (DiscussPost) event.getData().get("discussPost");
                        discussPostService.updateDiscussPost(discussPost);
                    } else {
                        DiscussPost discussPost = new DiscussPost();
                        discussPost.setUserId((Integer) event.getData().get("UserId"));
                        discussPost.setTitle((String) event.getData().get("Title"));
                        discussPost.setContent((String) event.getData().get("Content"));
                        discussPost.setCreateTime(DateUtil.nowTime());
                        discussPost.setTheme((String) event.getData().get("Theme"));
                        discussPost.setType(0);
                        discussPost.setStatus(0);
                        discussPost.setCommentCount(0);
                        discussPost.setScore(0.0);
//                    logger.info("postservice add now....");
                        discussPostService.addDiscussPost(discussPost);
                        // 计算帖子分数
                        String redisKey = RedisKeyUtil.getPostScoreKey();
                        redisTemplate.opsForSet().add(redisKey, discussPost.getId());
                    }
                } else {
                    return;
                }
                break;
            case TOPIC_DELETE: {
                int id = event.getEntityId();
                discussPostService.updateStatus(id, TYPE_TWE);
                break;
            }
            case TOPIC_CHANGE: {
                int id = event.getEntityId();
                int status = (int) event.getData().get("status");
                discussPostService.updateStatus(id, status);
                break;
            }
        }
        sendMsg.searchEvent(event);
        return ;
    }

    @RabbitListener(queues = RabbitmqConfig.QUEUE_SEARCH_AD)
    public void handleSearch(org.springframework.amqp.core.Message message, Channel channel) throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        if (message.getBody()== null ) {
            logger.error("消息的内容为空");
            return ;
        }
        Event event = JSONObject.parseObject(message.getBody(), Event.class);
        if (event == null) {
            logger.error("消息格式错误");
            return ;
        }
        if(event.getTopic().equals(TOPIC_PUBLISH)||event.getTopic().equals(TOPIC_CHANGE)){
            DiscussPost discussPost = discussPostService.findDiscussPostById(event.getEntityId());
            elasticsearchService.saveDiscusspost(discussPost);
            return ;
        }else if(event.getTopic().equals(TOPIC_DELETE)){
            elasticsearchService.saveDiscusspost(discussPostService.findDiscussPostById(event.getEntityId()));
            return ;
        }
        return ;
    }

    @RabbitListener(queues = RabbitmqConfig.QUEUE_READED)
    private void handleReaded(String record){
        if (record== null) {
            logger.error("消息的内容为空");
            return ;
        }
        Event event = JSONObject.parseObject(record, Event.class);
        if (event == null) {
            logger.error("消息格式错误");
            return ;
        }
        Readed readed=new Readed();
        readed.setUserId(event.getUserId());
        readed.setTargetId(event.getEntityId());
        readed.setReadTime(LocalDateTime.now());
        readed.setTheme((String) event.getData().get("theme"));
        historyService.addReaded(readed);
        return ;
    }

    @RabbitListener(queues = RabbitmqConfig.QUEUE_HISTORY)
    private void handleHistory(String record){
        if (record== null ) {
            logger.error("消息的内容为空");
            return ;
        }
        Event event = JSONObject.parseObject(record, Event.class);
        if (event == null) {
            logger.error("消息格式错误");
            return ;
        }
        HistorySeach seach=new HistorySeach();
        seach.setUserId(event.getUserId());
        seach.setContent((String) event.getData().get("keyword"));
        seach.setSeachTime(LocalDateTime.now());
        historyService.addHistory(seach);
        return ;
    }

    @RabbitListener(queues = RabbitmqConfig.QUEUE_EMAIL)
    private void handleMail(String record) throws MessagingException {
        if (record== null) {
            logger.error("消息的内容为空");
            return ;
        }
        Event event = JSONObject.parseObject(record, Event.class);
        if (event == null) {
            logger.error("消息格式错误");
            return ;
        }
        if(event.getEntityId()<=1){
            mainService.htmlMail(event);
        }
    }

}

